package com.mf.ergate.service.wx.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mf.ergate.service.wx.WeixinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 微信相关Service层实现类
 * User: zhaoming
 * DateTime: 2019-01-27
 * To change this template use File | Settings | File Templates.
 **/
@Service
public class WeixinServiceImpl implements WeixinService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${appid}")
    private String appid;
    @Value("${secret}")
    private String secret;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 登录凭证校验
     * @param code 登录时获取的code
     * @return 用户身份
     */
    public JSONObject code2Session(String code){
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code");
        url.append(String.format("&appid=%s", appid));
        url.append(String.format("&secret=%s", secret));
        url.append(String.format("&js_code=%s", code));
        return JSON.parseObject(restTemplate.getForObject(url.toString(), String.class));
    }

}
